import datetime
import models
import logging
import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.api import memcache

ONE_DAY = 86400


class BaseAdminHandler(webapp.RequestHandler):
  """Base handler class for admin users of the system. Internal only."""

  def __init__(self):
    webapp.RequestHandler.__init__(self)
    #check if user is googler
    self.username = users.get_current_user().nickname()
    self.admin = True if self.username.endswith('@google.com') else False

  def get(self):
    if self.admin:
      self.GetRequest()
    else:
      message = 'You are not an admin.'
      template_values = {'username': self.username,
                         'error_message': message}
      self.response.out.write(template.render(
          'templates/error_message.html', template_values))

  def GetRequest(self):
    """Delegate get handler should be over-ridden by subclasses."""
    pass

  def Render(self, template_file, template_values={}):
    username = self.username.split('@')[0]
    base_template_values = {'username': username}

    base_template_values.update(template_values)
    template_file = 'templates/%s' % template_file
    self.response.out.write(template.render(
        template_file, base_template_values))

  def SendJson(self, data):
    self.response.headers['Content-Type'] = 'application/json; charset=utf-8;'
    self.response.out.write(simplejson.dumps(data))


class BaseUserHandler(webapp.RequestHandler):
  """Base web handler for non google users."""
  def __init__(self):
    webapp.RequestHandler.__init__(self)
    self.today = datetime.datetime.now()
    delta = datetime.timedelta(days=1)
    self.new_videos_from_date = self.today - delta

    username = users.get_current_user().nickname()
    if not username.endswith('@gmail.com'):
      if not username.endswith('@google.com'):
        username = '%s@gmail.com' % username
    
    self.user = models.User.get_or_insert(
      username, username=username, last_accessed=self.today)
    #Check access rights, user can only be assigned to one org.
    access = models.UserAccessRights.all().filter('username', self.user).get()
    if access and access.organization.status == 'ENABLED':
      self.access = access
      self.partners = self._GetPartnersList()
      self.playlists = self._GetPlaylists()
      self.tags = self._GetTagsList()
    else:
      self.access = None

  def _GetPlaylists(self):
    playlists = memcache.get('%s_playlists' % self.access.organization.key())
    if not playlists:
      playlists = models.PlaylistAssociation.all().filter(
          'organization', self.access.organization).fetch(100)
      memcache.set('%s_playlists' % self.access.organization.key(),
                   playlists)
    return playlists

  def _GetTagsList(self):
    """Returns an aggregated list of tags created by the admin, and custom tags."""
    #TODO:memcache this request.
    tags = memcache.get('%s_tags' % self.access.organization.key())
    if not tags:
      org_tags = models.Tags.all().filter(
          'organization', self.access.organization).fetch(100)

      tags = [tag.name for tag in org_tags]
      memcache.set('%s_tags' % self.access.organization.key(), tags)

    return tags

  def _GetPartnersList(self):
    partners = memcache.get('%s_partners' % self.access.organization.org_key())
    if not partners:
      partners = models.PartnerAssociation.all().filter(
          'organization', self.access.organization.key()).fetch(1000)
      partners = [partner.partners.channel_name  for partner in partners]
      memcache.set('%s_partners' % self.access.organization.org_key(), partners)
    #TODO: Raise error if there are no partners in this list
    return partners

  def get(self):
    if self.access:
      self.GetRequest()
    else:
      message = 'Sorry, You do not have access to use this site.'
      template_values = {'error_message': message}
      self.response.out.write(template.render(
          'templates/error_message.html', template_values))

  def GetRequest(self):
    """Delegate get handler should be over-ridden by subclasses."""
    pass

  def Render(self, template_file, template_values={}):
    base_template_values = {
        'campaign_name': self.access.organization.name,
        'username': self.access.username.username}
    base_template_values.update(template_values)
    template_file = 'templates/%s' % template_file
    self.response.out.write(template.render(
        template_file, base_template_values))

  def SendJson(self, data):
    self.response.headers['Content-Type'] = 'application/json; charset=utf-8;'
    self.response.out.write(simplejson.dumps(data))
